package com.eightbears.beboy.ui.user.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.PostPackageAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.entity.HongBaoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_USER_RED;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.SystemMessageActivity.PARAMS_IS_SYSTEM_MESSAGE;

public class PostRedFragment extends BaseFragment implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private boolean isSystem =false;
    private PostPackageAdapter mPostPackageAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_post_red, container, false);
        ButterKnife.bind(this, view);
        isSystem = getActivity().getIntent().getBooleanExtra(PARAMS_IS_SYSTEM_MESSAGE, false);
        initView();
        initData();
        return view;
    }

    @Override
    protected void initView() {
        initAdapter();
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {

    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_USER_RED)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", "1")
                .addParams("size", "1000")
                .addParams("type", HongBaoEntity.TYPE_POST)
                .addParams("status", "1")
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                HongBaoEntity hongBaoEntity = GsonUtil.fromJson(response, HongBaoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(hongBaoEntity.getStatus_code())) {
                    isEnd = hongBaoEntity.getData().getIs_end();
                    if (page == 1) {
                        mPostPackageAdapter.setNewData(hongBaoEntity.getData().getList());
                        if (hongBaoEntity.getData().getList().size() == 0)
                            view_empty.setVisibility(View.VISIBLE);
                        else
                            view_empty.setVisibility(View.GONE);
                    } else {
                        mPostPackageAdapter.addData(hongBaoEntity.getData().getList());
                        mPostPackageAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPostPackageAdapter = new PostPackageAdapter();
        mPostPackageAdapter.openLoadAnimation();
        mPostPackageAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(mPostPackageAdapter);
        mPostPackageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.ll_item) {
                    if(!isSystem) {
                        EventBus.getDefault().post(adapter.getData().get(position));
                        getActivity().finish();
                    }
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        mPostPackageAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mPostPackageAdapter.getData().clear();
                getData();
                mPostPackageAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mPostPackageAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mPostPackageAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
